package br.com.rapidrest.demo.web.engine.phonebook;

import java.io.Serializable;

import javax.ejb.EJB;

import br.com.rapidrest.annotation.Inject;
import br.com.rapidrest.demo.domain.PhoneBook;
import br.com.rapidrest.demo.domain.PhoneEntry;
import br.com.rapidrest.demo.service.PhoneBookService;
import br.com.rapidrest.demo.web.engine.Home;
import br.com.rapidrest.response.RestURL;
import br.com.rapidrest.util.MessagesBundle;

public class EditPhoneEntry implements Serializable {

	private static final long serialVersionUID = 1708574767856681234L;

	@Inject
	private MessagesBundle messages;

	@EJB
	private PhoneBookService phoneBookService;
	
	private PhoneBook phoneBook;
	
	private PhoneEntry phoneEntry;

	private String entryName;

	private String entryPhone;
	
	public Object init(Long phoneBookId, Long entryId) {
		phoneBook = phoneBookService.findPhoneBook(phoneBookId);
		if (phoneBook == null) {
			return Home.class;
		}
		for (PhoneEntry entry : phoneBook.getEntries()) {
			if (entry.getId().equals(entryId)) {
				phoneEntry = entry;
				break;
			}
		}
		if (phoneEntry == null) {
			return Home.class;
		}
		return null;
	}
	
	public Object save(Long phoneBookId, Long entryId) {
		phoneBook = phoneBookService.findPhoneBook(phoneBookId);
		if (phoneBook == null) {
			return Home.class;
		}
		for (PhoneEntry entry : phoneBook.getEntries()) {
			if (entry.getId().equals(entryId)) {
				phoneEntry = entry;
				break;
			}
		}
		if (phoneEntry == null) {
			return Home.class;
		}
		
		phoneEntry.setName(entryName);
		phoneEntry.setPhone(entryPhone);
		
		phoneBookService.updatePhoneEntry(phoneEntry);
		
		return RestURL.goTo(EditPhoneBook.class, phoneBook.getId());
	}
	
	public MessagesBundle getMessages() {
		return messages;
	}

	public PhoneEntry getPhoneEntry() {
		return phoneEntry;
	}

	public PhoneBook getPhoneBook() {
		return phoneBook;
	}

	public void setEntryName(String entryName) {
		this.entryName = entryName;
	}

	public void setEntryPhone(String entryPhone) {
		this.entryPhone = entryPhone;
	}

}